import { useState, useEffect, useRef, useMemo } from 'react';
import { request } from '@/api/request';

// 选项卡key到type的映射
const tabTypeMap: Record<string, string> = {
  anime_girl: 'AnimeGirl',
  anime_man: 'AnimeMan',
  girl: 'Girl',
  man: 'Man',
};

// 语言code到接口参数的映射
const langMap: Record<string, string> = {
  zh: 'CN',
  'zh-CN': 'CN',
  'zh-TW': 'CN',
  en: 'EN',
  'en-US': 'EN',
  'en-GB': 'EN',
  ja: 'JP',
  'ja-JP': 'JP',
};

// 获取语言映射，支持更复杂的语言代码
const getLangCode = (language: string): string => {
  // 直接匹配
  if (langMap[language]) {
    return langMap[language];
  }
  // 匹配前缀（如 zh-CN -> zh）
  const prefix = language.split('-')[0];
  if (langMap[prefix]) {
    return langMap[prefix];
  }
  // 默认返回EN
  return 'EN';
};

// 🚀 性能优化：动态调整页面大小，首屏优先加载更少数据
const getPageSize = (isFirstLoad: boolean): number => {
  if (isFirstLoad) {
    // 首屏只加载6个，加快首次渲染
    return 6;
  }
  return 8; // 后续加载正常数量
};

// 缓存数据类型定义
interface CacheData {
  list: any[];
  total: number;
  totalPages: number;
}

// hook返回值类型定义
interface UseHomeDataReturn {
  data: any[];
  loading: boolean;
  hasMore: boolean;
  totalPages: number;
  checkingTotal: boolean;
  page: number;
  setPage: React.Dispatch<React.SetStateAction<number>>;
}

export const useHomeData = (activeTab: string, language: string): UseHomeDataReturn => {
  // 状态管理
  const [data, setData] = useState<Array<any>>([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(false);
  const [totalPages, setTotalPages] = useState(1);
  const [checkingTotal, setCheckingTotal] = useState(false);

  // ref管理
  const didFirstLoad = useRef(false);
  const lastCheckedTab = useRef('');
  // 🔧 新增：用于管理setTimeout的ref，防止内存泄漏
  const fetchDataTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const reloadDataTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  // 🚀 性能优化：缓存当前请求的AbortController，避免重复请求
  const currentRequestRef = useRef<AbortController | null>(null);
  // 🔧 修复关键：使用请求ID来确保只有正确的请求才能更新状态
  const currentRequestIdRef = useRef<string>('');

  // 🚀 性能优化：使用useMemo缓存缓存键计算
  const cacheKey = useMemo(() => {
    const type = tabTypeMap[activeTab] || 'AnimeGirl';
    const lang = getLangCode(language);
    return `${type}_${lang}`;
  }, [activeTab, language]);

  // 缓存操作函数
  const getCache = (): Record<string, CacheData> => {
    const allCacheRaw = localStorage.getItem('HomeList');
    return allCacheRaw ? JSON.parse(allCacheRaw) : {};
  };

  const setCache = (key: string, value: CacheData) => {
    const allCache = getCache();
    allCache[key] = value;
    localStorage.setItem('HomeList', JSON.stringify(allCache));
  };

  // 检查远程total是否有更新（轻量级请求）
  const checkRemoteTotal = async (type: string, lang: string, cacheKey: string) => {
    if (checkingTotal) return; // 避免重复检查
    
    setCheckingTotal(true);
    try {
      const res = await request.post('/api/ai-persons/', {
        page: 1,
        pageSize: 1, // 只要1条数据，主要获取total信息
        type: type,
        language: lang,
        information: false
      });
      
      if (res.status === 200 && res.data && res.data.data) {
        const remoteTotal = res.data.data.pagination?.total || 0;
        const allCache = getCache();
        const localTotal = allCache[cacheKey]?.total || 0;
        
        // 如果远程total与本地不同，更新缓存中的total
        if (remoteTotal !== localTotal && allCache[cacheKey]) {
          allCache[cacheKey].total = remoteTotal;
          allCache[cacheKey].totalPages = res.data.data.pagination?.totalPages || 1;
          setCache(cacheKey, allCache[cacheKey]);
          
          // 更新UI状态
          setTotalPages(allCache[cacheKey].totalPages);
          setHasMore(data.length < remoteTotal);
          
          // console.log(`检测到${type}_${lang}数据更新: 本地total=${localTotal}, 远程total=${remoteTotal}`);
        }
      }
    } catch (error) {
      // console.error('检查total失败:', error);
      console.error('check total failed',error);
    } finally {
      setCheckingTotal(false);
    }
  };

  // 发起数据请求
  const fetchData = async (pageNum: number, type: string, lang: string, cacheKey: string, cacheData: CacheData) => {
    if (loading) return;
    
    // 🔧 修复：在发起请求前检查当前选项卡状态是否还匹配
    const currentType = tabTypeMap[activeTab] || 'AnimeGirl';
    const currentLang = getLangCode(language);
    const currentCacheKey = `${currentType}_${currentLang}`;
    
    if (currentCacheKey !== cacheKey) {
      // console.log(`选项卡已切换，取消数据请求: ${cacheKey} -> ${currentCacheKey}`);
      return;
    }
    
    setLoading(true);
    
    // 🚀 性能优化：首屏使用更小的页面大小，加快首次渲染
    const pageSize = getPageSize(pageNum === 1 && !didFirstLoad.current);
    
    // 🔧 修复关键：保存请求时的cacheKey，用于后续验证
    const requestCacheKey = cacheKey;
    
    // 🔧 修复关键：生成唯一请求ID，确保只有最新的请求能更新状态
    const requestId = `${requestCacheKey}_${Date.now()}_${Math.random()}`;
    currentRequestIdRef.current = requestId;
    
    try {
      const res = await request.post('/api/ai-persons/', {
        page: pageNum,
        pageSize: pageSize,
        type: type,
        language: lang,
        information: false
      });
      
      if (res.status === 200 && res.data && res.data.data) {
        // 新的数据结构：数据在 data.list 中
        const newList = (res.data.data.list || []).map((item: any) => ({
          // 保持现有字段结构，但从新的API结构中提取
          ...item,
          // 从 information 对象中提取用户名和年龄
          username: item.information?.name || '',
          age: item.information?.age || 0,
          gender: item.information?.gender || '',
          zodiac: item.information?.zodiac || '',
          occupation: item.information?.occupation || '',
          language: item.information?.language || '',
          // 映射字段名变化
          isPremium: item.is_premium || false,
          // 保持描述字段的截取逻辑
          description: item.description ? item.description.slice(0, 50) : '',
        }));
        const responseTotalPages = res.data.data.pagination?.totalPages || 1;
        const responseTotal = typeof res.data.data.pagination?.total === 'number' ? res.data.data.pagination.total : newList.length;
        
        // 🔧 修复关键：只有当前选项卡匹配请求时的选项卡才更新状态
        const finalCurrentType = tabTypeMap[activeTab] || 'AnimeGirl';
        const finalCurrentLang = getLangCode(language);
        const finalCurrentCacheKey = `${finalCurrentType}_${finalCurrentLang}`;
        
        if (finalCurrentCacheKey !== requestCacheKey) {
          // console.log(`数据响应时选项卡已切换，丢弃数据更新: ${requestCacheKey} -> ${finalCurrentCacheKey}`);
          // 🔧 修复：即使不更新UI状态，也要更新缓存，避免重复请求
          const mergedList = [...(cacheData.list || []), ...newList].filter(
            (item, idx, arr) => arr.findIndex(i => i.id === item.id) === idx
          );
          setCache(requestCacheKey, { list: mergedList, total: responseTotal, totalPages: responseTotalPages });
          return;
        }
        
        // 🔧 修复关键：检查请求ID，确保只有最新的请求能更新状态
        if (currentRequestIdRef.current !== requestId) {
          // console.log(`数据响应时发现过期请求，丢弃数据更新: ${requestId} (当前: ${currentRequestIdRef.current})`);
          // 🔧 修复：即使不更新UI状态，也要更新缓存，避免重复请求
          const mergedList = [...(cacheData.list || []), ...newList].filter(
            (item, idx, arr) => arr.findIndex(i => i.id === item.id) === idx
          );
          setCache(requestCacheKey, { list: mergedList, total: responseTotal, totalPages: responseTotalPages });
          return;
        }
        
        // 合并缓存和新数据时用id去重
        const mergedList = [...(cacheData.list || []), ...newList].filter(
          (item, idx, arr) => arr.findIndex(i => i.id === item.id) === idx
        );
        
        // 更新缓存
        setCache(requestCacheKey, { list: mergedList, total: responseTotal, totalPages: responseTotalPages });
        
        // 🔧 修复：只有当前选项卡匹配时才更新UI状态
        const displayData = mergedList.slice(0, pageNum * pageSize);
        setData(displayData);
        setTotalPages(responseTotalPages);
        setHasMore(pageNum * pageSize < responseTotal);
      } else {
        // 🔧 修复：在错误处理前检查选项卡状态
        const errorCurrentType = tabTypeMap[activeTab] || 'AnimeGirl';
        const errorCurrentLang = getLangCode(language);
        const errorCurrentCacheKey = `${errorCurrentType}_${errorCurrentLang}`;
        
        // 🔧 修复：始终更新缓存，避免重复请求
        setCache(requestCacheKey, { list: [], total: 0, totalPages: 1 });
        
        // 🔧 修复：只有当前选项卡匹配且请求ID匹配时才更新UI状态
        if (errorCurrentCacheKey === requestCacheKey && currentRequestIdRef.current === requestId) {
          setData([]);
          setTotalPages(1);
          setHasMore(false);
        } else {
          // console.log(`接口异常时选项卡已切换或请求过期，跳过UI状态更新: ${requestCacheKey} -> ${errorCurrentCacheKey}, requestId: ${requestId}`);
        }
      }
    } catch (error) {
      // console.error('数据请求失败:', error);
      console.error('load data failed',error);
      
      // 🔧 修复：在错误处理前检查选项卡状态
      const errorCurrentType = tabTypeMap[activeTab] || 'AnimeGirl';
      const errorCurrentLang = getLangCode(language);
      const errorCurrentCacheKey = `${errorCurrentType}_${errorCurrentLang}`;
      
      // 🔧 修复：始终更新缓存，避免重复请求
      setCache(requestCacheKey, { list: [], total: 0, totalPages: 1 });
      
      // 🔧 修复：只有当前选项卡匹配且请求ID匹配时才更新UI状态
      if (errorCurrentCacheKey === requestCacheKey && currentRequestIdRef.current === requestId) {
        setData([]);
        setTotalPages(1);
        setHasMore(false);
      } else {
        // console.log(`请求失败时选项卡已切换或请求过期，跳过UI状态更新: ${requestCacheKey} -> ${errorCurrentCacheKey}, requestId: ${requestId}`);
      }
    } finally {
      // 🔧 修复关键：只有当前选项卡匹配且请求ID匹配时才设置loading为false
      const finalCurrentType = tabTypeMap[activeTab] || 'AnimeGirl';
      const finalCurrentLang = getLangCode(language);
      const finalCurrentCacheKey = `${finalCurrentType}_${finalCurrentLang}`;
      
      if (finalCurrentCacheKey === requestCacheKey && currentRequestIdRef.current === requestId) {
        setLoading(false);
      } else {
        // console.log(`请求完成时选项卡已切换或请求过期，跳过loading状态更新: ${requestCacheKey} -> ${finalCurrentCacheKey}, requestId: ${requestId}`);
      }
    }
  };

  // 监听tab/语言变化，立即无感渲染缓存数据
  useEffect(() => {
    const type = tabTypeMap[activeTab] || 'AnimeGirl';
    const lang = getLangCode(language);
    const cacheKey = `${type}_${lang}`;
    const tabKey = `${activeTab}_${language}`;
    
    // console.log(`语言切换: ${language} -> ${lang}, 缓存键: ${cacheKey}`, {
    //   found: !!getCache()[cacheKey],
    //   listLength: (getCache()[cacheKey]?.list?.length || 0)
    // });
    
    // 🔧 修复：防止快速切换时的状态混乱，先清理之前的timeout
    if (fetchDataTimeoutRef.current) {
      clearTimeout(fetchDataTimeoutRef.current);
      fetchDataTimeoutRef.current = null;
    }
    
    // 🔧 修复关键：更新请求ID，使之前的请求失效
    currentRequestIdRef.current = `${cacheKey}_tab_switch_${Date.now()}`;
    
    // 重置分页相关状态
    setPage(1);
    setLoading(false);
    didFirstLoad.current = false;
    
    // 获取缓存数据
    const allCache = getCache();
    const cacheData = allCache[cacheKey] || { list: [], total: 0, totalPages: 1 };
    
    // 🔧 修复：使用防抖延迟处理，避免快速切换时的竞态条件
    const debounceTime = 50; // 50ms防抖
    
    const handleTabSwitch = () => {
      // 🔧 修复关键：在更新状态前再次检查选项卡状态
      const verifyCurrentType = tabTypeMap[activeTab] || 'AnimeGirl';
      const verifyCurrentLang = getLangCode(language);
      const verifyCurrentCacheKey = `${verifyCurrentType}_${verifyCurrentLang}`;
      
      if (verifyCurrentCacheKey !== cacheKey) {
        // console.log(`handleTabSwitch: 选项卡已切换，跳过状态更新: ${cacheKey} -> ${verifyCurrentCacheKey}`);
        return;
      }
      
      // 无感渲染：直接设置缓存数据，不先清空
      if (cacheData.list && cacheData.list.length > 0) {
        // 🚀 性能优化：首屏显示较少数据
        const firstPageSize = getPageSize(true);
        const displayData = cacheData.list.slice(0, firstPageSize);
        // console.log(`语言切换数据更新: ${language} -> ${lang}`, {
        //   cacheKey,
        //   dataCount: displayData.length,
        //   firstUser: displayData[0]?.username
        // });
        
        // 🔧 修复：确保状态更新的原子性，避免被其他选项卡的状态覆盖
        setData([...displayData]); // 强制创建新数组引用
        setTotalPages(cacheData.totalPages || 1);
        setHasMore(firstPageSize < cacheData.total);
        
        // 即使有缓存，也要检查是否需要更新数据
        // 如果缓存数据不足一页，强制请求更多数据
        if (cacheData.list.length < firstPageSize && cacheData.list.length < cacheData.total) {
          fetchDataTimeoutRef.current = setTimeout(() => {
            // 🔧 修复：添加额外的检查，确保当前选项卡没有变化
            const currentType = tabTypeMap[activeTab] || 'AnimeGirl';
            const currentLang = getLangCode(language);
            const currentCacheKey = `${currentType}_${currentLang}`;
            
            if (currentCacheKey === cacheKey && !loading) {
              fetchData(1, type, lang, cacheKey, cacheData);
            }
            fetchDataTimeoutRef.current = null;
          }, 100);
        }
      } else {
        // 🔧 修复：只有在当前选项卡确实没有缓存时才清空，防止被其他选项卡影响
        // console.log(`没有缓存数据，为当前选项卡清空列表: ${cacheKey}`);
        setData([]);
        setHasMore(true);
        setTotalPages(1);
      }
    };
    
    // 🔧 修复：使用防抖处理，防止快速切换时的状态混乱
    fetchDataTimeoutRef.current = setTimeout(() => {
      // 再次检查当前选项卡是否还是目标选项卡
      const currentType = tabTypeMap[activeTab] || 'AnimeGirl';
      const currentLang = getLangCode(language);
      const currentCacheKey = `${currentType}_${currentLang}`;
      
      if (currentCacheKey === cacheKey) {
        handleTabSwitch();
      }
      
      fetchDataTimeoutRef.current = null;
    }, debounceTime);
    
    // 每次切换都检查远程total（防重复）
    if (lastCheckedTab.current !== tabKey) {
      lastCheckedTab.current = tabKey;
      checkRemoteTotal(type, lang, cacheKey);
    }
  }, [activeTab, language]);

  // 检查是否需要请求数据（分页或首次加载）
  useEffect(() => {
    // 避免在 loading 时重复请求
    if (loading) return;
    
    const type = tabTypeMap[activeTab] || 'AnimeGirl';
    const lang = getLangCode(language);
    const cacheKey = `${type}_${lang}`;
    const allCache = getCache();
    const cacheData = allCache[cacheKey] || { list: [], total: 0, totalPages: 1 };
    
    // 🔧 修复：添加防抖处理，避免快速切换时的重复请求
    const requestDebounceTime = 100; // 100ms防抖
    
    const handleDataRequest = () => {
      // 🔧 修复：再次检查当前选项卡是否还是目标选项卡
      const currentType = tabTypeMap[activeTab] || 'AnimeGirl';
      const currentLang = getLangCode(language);
      const currentCacheKey = `${currentType}_${currentLang}`;
      
      if (currentCacheKey !== cacheKey) {
        // console.log(`选项卡已切换，取消数据请求: ${cacheKey} -> ${currentCacheKey}`);
        return;
      }
      
      // 如果是分页请求（page > 1），检查缓存是否足够
      if (page > 1) {
        // 🚀 性能优化：后续页面使用正常页面大小
        const normalPageSize = getPageSize(false);
        const neededData = (page - 1) * getPageSize(true) + (page - 1) * normalPageSize;
        if (cacheData.list.length >= neededData || cacheData.list.length >= cacheData.total) {
          // 🔧 修复：在更新状态前检查选项卡状态
          const verifyCurrentType = tabTypeMap[activeTab] || 'AnimeGirl';
          const verifyCurrentLang = getLangCode(language);
          const verifyCurrentCacheKey = `${verifyCurrentType}_${verifyCurrentLang}`;
          
          if (verifyCurrentCacheKey === cacheKey) {
            // 缓存足够，直接显示
            setData(cacheData.list.slice(0, neededData));
            setHasMore(neededData < cacheData.total);
          } else {
            // console.log(`分页请求时选项卡已切换，跳过状态更新: ${cacheKey} -> ${verifyCurrentCacheKey}`);
          }
          return;
        }
        // 缓存不够，需要请求更多数据
      } else {
        // page === 1 的情况
        if (didFirstLoad.current) return; // 避免重复请求
        didFirstLoad.current = true;
        
        const firstPageSize = getPageSize(true);
        // 如果缓存为空，需要请求
        if (cacheData.list.length === 0) {
          // 缓存为空，需要请求
        } else if (cacheData.list.length >= cacheData.total) {
          // 缓存数据已经是全部数据，不需要请求
          return;
        } else if (cacheData.list.length < firstPageSize && cacheData.list.length < cacheData.total) {
          // 缓存数据不足一页且还有更多数据，需要请求
        } else {
          // 其他情况：有缓存且大于等于一页但可能不完整，继续请求
        }
      }
      
      // 发起数据请求
      fetchData(page, type, lang, cacheKey, cacheData);
    };
    
    // 🔧 修复：使用防抖处理，避免快速切换时的重复请求
    const timeoutId = setTimeout(() => {
      handleDataRequest();
    }, requestDebounceTime);
    
    return () => {
      clearTimeout(timeoutId);
    };
  }, [page, activeTab, language]);

  // 监听页面刷新事件，重新获取数据
  useEffect(() => {
    const handlePageRefreshReload = () => {
      // console.log('🏠 HomeData: 接收到页面刷新重载事件，重新获取数据');
      
      // 清除当前缓存数据
      localStorage.removeItem('HomeList');
      
      // 重置状态
      setData([]);
      setPage(1);
      setTotalPages(1);
      setHasMore(true);
      didFirstLoad.current = false;
      lastCheckedTab.current = '';
      
      // 延迟重新加载数据
      // 🔧 修复：清理之前的timeout并保存新的timeout引用
      if (reloadDataTimeoutRef.current) {
        clearTimeout(reloadDataTimeoutRef.current);
      }
      reloadDataTimeoutRef.current = setTimeout(() => {
        const type = tabTypeMap[activeTab] || 'AnimeGirl';
        const lang = getLangCode(language);
        const cacheKey = `${type}_${lang}`;
        const cacheData = { list: [], total: 0, totalPages: 1 };
        
        fetchData(1, type, lang, cacheKey, cacheData);
        reloadDataTimeoutRef.current = null;
      }, 200);
    };

    window.addEventListener('pageRefreshDataReload', handlePageRefreshReload);
    
    return () => {
      window.removeEventListener('pageRefreshDataReload', handlePageRefreshReload);
    };
  }, [activeTab, language]);

  // 🔧 新增：组件卸载时清理所有timeout，防止内存泄漏
  useEffect(() => {
    return () => {
      if (fetchDataTimeoutRef.current) {
        clearTimeout(fetchDataTimeoutRef.current);
        fetchDataTimeoutRef.current = null;
      }
      if (reloadDataTimeoutRef.current) {
        clearTimeout(reloadDataTimeoutRef.current);
        reloadDataTimeoutRef.current = null;
      }
    };
  }, []);

  return {
    data,
    loading,
    hasMore,
    totalPages,
    checkingTotal,
    page,
    setPage,
  };
}; 